//
//  SYHelper.swift
//  Entrance
//
//  Created by chunhuiLai on 2018/1/12.
//  Copyright © 2018年 chunhuiLai. All rights reserved.
//

import Foundation

public typealias JSONDictionary = [String : Any]

//MARK: - GCD_Task
typealias GCD_Task = (_ cancel: Bool) -> Void

@discardableResult
func delay(_ time: TimeInterval, task:@escaping () -> ()) -> GCD_Task? {
    
    func dispatch_later(_ block:@escaping ()->()) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: block)
    }
    var closure: (()->Void)? = task
    var result: GCD_Task?
    
    let delayedClosure: GCD_Task = {
        cancel in
        if let internalClosure = closure {
            if cancel == false {
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        closure = nil
        result = nil
    }
    
    result = delayedClosure
    
    dispatch_later { () -> () in
        if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    
    return result
}

func cancel(_ task: GCD_Task?) {
    task?(true)
}
